package light.mvc.service.record.impl;

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import light.mvc.dao.BaseDaoI;
import light.mvc.model.record.Troom;
import light.mvc.model.record.TroomSchedule;
import light.mvc.model.sys.Tuser;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.base.RoomEvent;
import light.mvc.pageModel.meetingroom.MeetingroomEvent;
import light.mvc.pageModel.meetingroom.RegularPageModel;
import light.mvc.pageModel.record.RoomSchedule;
import light.mvc.service.record.RoomScheduleServiceI;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;

@Service
public class RoomScheduleServiceImpl implements RoomScheduleServiceI {
	protected HibernateTemplate hibernateTemplate;

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	public DetachedCriteria getCriteria() {
		return DetachedCriteria.forClass(TroomSchedule.class);
	}

	@Autowired
	private BaseDaoI<TroomSchedule> roomScheduleDao;
	
	@Autowired
	private BaseDaoI<Troom> roomDao;
	@Autowired
	private BaseDaoI<Tuser> userDao;

	@Override
	public List<RoomEvent> getDurationEvent(RoomSchedule roomSchedule) {
		List<RoomSchedule> ul = new ArrayList<RoomSchedule>();
		long id = roomSchedule.getRoomid();
		String hql = " from TroomSchedule t where t.room.id =" + id;
		List<TroomSchedule> l = this.roomScheduleDao.find(hql);
		for (TroomSchedule t : l) {
			RoomSchedule u = new RoomSchedule();
			BeanUtils.copyProperties(t, u);
			u.setName(t.getName() + " " + t.getUser().getName());
			ul.add(u);
		}

		List<RoomEvent> events = new ArrayList<RoomEvent>();
		for (RoomSchedule roomsc : ul) {
			RoomEvent event = new RoomEvent();
			event.setTitle(roomsc.getName());
			event.setStart(roomsc.getStart());
			event.setEditable(true);
			event.setId(roomsc.getId());
			event.setEnd(roomsc.getEnd());
			events.add(event);
		}
		return events;
	}

	public List<RoomSchedule> getAllDurationEvents() {
		List<RoomSchedule> ul = new ArrayList<RoomSchedule>();
		String hql = " from TroomSchedule t ";
		List<TroomSchedule> l = this.roomScheduleDao.find(hql);
		for (TroomSchedule t : l) {
			RoomSchedule u = new RoomSchedule();
			BeanUtils.copyProperties(t, u);
			u.setName(t.getName());
			ul.add(u);
		}
		return ul;
	}

	/**
	 * 检验同会议室下是否有会议与新增或修改后的会议的时间有重叠
	 * 
	 * @param start
	 *            会议开始时间
	 * @param end
	 *            会议结束时间
	 * @return false：有重叠，true：无重叠
	 */
	public boolean isLegalEvent(long start, long end, int id) {
		// return (n1 + n2 + n3) == 0 ? true : false;
		return false;
	}

	public List<TroomSchedule> getTodayEvent() {
		String sqlStr = "select x.*,y.name username,y.tel,y.email, z.name roomname from room_schedule x " + " left join user y on x.userid = y.id " + " left join room z on x.roomid=z.id " + " where to_days(start)=to_days(now()) order by start asc";
		System.out.println(sqlStr);
		return roomScheduleDao.find(sqlStr);
	}

	@Override
	public boolean orderRoomEvent(RoomEvent event) {
		TroomSchedule troomSchedule = new TroomSchedule();
		troomSchedule.setStart(event.getStart());
		troomSchedule.setEnd(event.getEnd());
		troomSchedule.setName(event.getName());
		troomSchedule.setUser(userDao.get(Tuser.class, event.getUserId().longValue()));
		troomSchedule.setRoom(roomDao.get(Troom.class, event.getRoomid().longValue()));
		roomScheduleDao.save(troomSchedule);
		return true;
	}

	@Override
	public boolean updateRoomEvent(RoomSchedule roomSchedule) {
		TroomSchedule troomSchedule = roomScheduleDao.get(TroomSchedule.class, roomSchedule.getId());
		long userIdFromDataBase = troomSchedule.getUser().getId();
		long userIdFormPage = roomSchedule.getUserid();
		if (userIdFromDataBase != userIdFormPage) {
			return false;
		}
		if (roomSchedule.getStart() != null) {
			troomSchedule.setStart(roomSchedule.getStart());
		}
		if (roomSchedule.getEnd() != null) {
			troomSchedule.setEnd(roomSchedule.getEnd());
		}
		if (roomSchedule.getName() != null) {
			troomSchedule.setName(roomSchedule.getName());
		}
		if (roomSchedule.getRoomName() != null) {
			Troom troom = roomDao.get("from Troom t where t.name='" + roomSchedule.getRoomName() + "'");
			troomSchedule.setRoom(troom);
		}
		if (roomSchedule.getUserid() != null) {
			Tuser tuser = userDao.get("from Tuser t where t.id='" + roomSchedule.getUserid() + "'");
			troomSchedule.setUser(tuser);
		}
		roomScheduleDao.update(troomSchedule);
		return true;
	}

	@Override
	public boolean deleteRoomEvent(RoomEvent event) {
		TroomSchedule t = new TroomSchedule();
		t.setId(event.getId());
		roomScheduleDao.delete(t);
		return true;
	}

	private String whereHql(RoomSchedule roomSchedule, Map<String, Object> params) {
		String hql = "";
		if (roomSchedule != null) {
			hql = hql + " where 1=1 ";
			if (roomSchedule.getName() != null) {
				hql = hql + " and t.name like :name";
				params.put("name", "%%" + roomSchedule.getName() + "%%");
			}
		}
		return hql;
	}

	private String orderHql(PageFilter ph) {
		String orderString = "";
		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}

	@Override
	public Object getEventById(MeetingroomEvent event) {
		TroomSchedule t = roomScheduleDao.get(TroomSchedule.class, Integer.valueOf(event.getId()).longValue());
		Troom troom = roomDao.get(Troom.class, t.getRoom().getId());
		MeetingroomEvent ev = new MeetingroomEvent();
		ev.setRoomName(troom.getName());
		ev.setStart(t.getStart());
		ev.setEnd(t.getEnd());
		ev.setTitle(t.getName());
		ev.setId(t.getId().intValue());
		return t;
	}

	@Override
	public boolean addRoomEvent(RegularPageModel regularPageModel) {
		Calendar datestart = new GregorianCalendar();
		Calendar dateend = new GregorianCalendar();
		datestart.setTime(regularPageModel.getStartDate());
		dateend.setTime(regularPageModel.getEndDate());

		Calendar c_begin = datestart;
		Calendar c_end = dateend;
		DateFormatSymbols dfs = new DateFormatSymbols();
		String[] weeks = dfs.getWeekdays();
		c_end.add(Calendar.DAY_OF_YEAR, 1); //
		int count = 1;
		while (c_begin.before(c_end)) {
			String regularDateTimeStart = "";
			String regularDateTimeEnd = "";
			if (c_begin.get(Calendar.DAY_OF_WEEK) == Integer.valueOf(regularPageModel.getWeek())) {
				System.out.println(weeks[c_begin.get(Calendar.DAY_OF_WEEK)]);
				try {
					Date date1;
					Date date2;
					regularDateTimeStart += new java.sql.Date(c_begin.getTime().getTime()) + " " + c_begin.get(Calendar.HOUR_OF_DAY) + ":" + c_begin.get(Calendar.MINUTE) + ":" + c_begin.get(Calendar.SECOND);
					date1 = (Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(regularDateTimeStart);
					regularDateTimeEnd += new java.sql.Date(c_begin.getTime().getTime()) + " " + c_end.get(Calendar.HOUR_OF_DAY) + ":" + c_end.get(Calendar.MINUTE) + ":" + c_end.get(Calendar.SECOND);
					date2 = (Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(regularDateTimeEnd);
					TroomSchedule t = new TroomSchedule();
					Tuser tuser = userDao.get(Tuser.class, Long.valueOf(regularPageModel.getLoginId()));
					t.setName(regularPageModel.getTitle());
					t.setUser(tuser);
					t.setStart(date1);
					t.setEnd(date2);
					t.setCreate_date(new Date(System.currentTimeMillis()));
					t.setRoom(roomDao.get(Troom.class, Long.valueOf(regularPageModel.getRoomId())));
					roomScheduleDao.save(t);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if (c_begin.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
				count++;
			}
			c_begin.add(Calendar.DAY_OF_YEAR, 1);
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void deleteRoomEvent(RegularPageModel regularPageModel) {
		DetachedCriteria dc0 = this.getCriteria();
		dc0.add(Restrictions.eq("start", regularPageModel.getStartDate()));
		System.out.println(regularPageModel.getStartDate());
		dc0.add(Restrictions.eq("end",regularPageModel.getEndDate()));
		List<TroomSchedule> tr = this.getHibernateTemplate().findByCriteria(dc0);
		Date createDate = tr.get(0).getCreate_date();
		DetachedCriteria dc = this.getCriteria();
		dc.add(Restrictions.eq("create_date", createDate));
		this.getHibernateTemplate().deleteAll(this.getHibernateTemplate().findByCriteria(dc));
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

}
